import { request } from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    typeList:[
      {
        id:0,
        name:'新品'
      }
    ],
    productList:[],
    newList:[],
    products:[],
    //左侧被选中
    currentIndex:0,
    toView:'',
    cart:[],
    cp_index: 0,
    leftTop: 0,
    left_item_height: 0,
    heightArr: 0,
    zindex: 0,
    oneShow: true,
    cartData: {}
  },

  /**
   * 生命周期函数--监听页面加载，在第一次打开页面的时候调用
   */
  onLoad: function (options) {

  },
  /**
   * 生命周期函数--监听页面显示，每次打开页面的时候调用
   */
  onShow(){
    this.getTypes();
    this.getCarts();
    this.getProducts();
  },
  onReady: function () {
    var that = this;
    var h = 0;
    var heightArr = [];
    wx.createSelectorQuery().select('.menu_item').boundingClientRect(function (rect) { //select会选择第一个类目的盒子
    }).exec(function (res) {
      that.setData({
        left_item_height: res[0].height
      })

    });

    wx.createSelectorQuery().selectAll('.product_item').boundingClientRect(function (rect) { //selectAll会选择所要含有该类名的盒子
    }).exec(function (res) {
      res[0].forEach((item) => {
        h += item.height;
        heightArr.push(h);
      })
      that.setData({
        heightArr: heightArr
      })
    })
  },
  onHide: function() {
    this.setCart();
  },
  //当redirectTo或navigateBack的时候调用。
  onUnload: function() {
    this.setCart();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //调用刷新时将执行的方法
    this.getTypes();
    this.getProducts();
    this.getCarts();
  },
  async getTypes(){
    let typeList=[
      {
        id:0,
        name:'新品'
      }
    ];
    const res = await request({ url: "goodsType/parentList",  method: 'GET' });
    typeList = typeList.concat(res.data)
    this.setData({
      typeList
    })
  },
  async getProducts(){
    const res = await request({ url: "product/allProduct",  method: 'GET' });
    const productList = res.data.allProduct;
    const newList = res.data.allNew;
    let products = newList.concat(productList)
    this.setData({
      products,
      productList,
      newList
    })
  },
  async getCarts(){
    //从服务器获取购物车数据
    const userInfo = wx.getStorageSync('userinfo')
    if(userInfo){
      const res = await request({ url: "shopCart/getCart", data: {userId:userInfo.id}, method: 'GET' });
      let cart = res.data;
      //获取购物车遍历添加进cartData
      let cartData = this.data.cartData;
      cart.forEach(v=>{
        cartData[v.goodsId] = v.amount;
      })
      this.setData({
        cartData
      })
      this.changeCart(cart);
    }
    wx.stopPullDownRefresh();
  },
  async setCart(){
    const cart = this.data.cart;
    if(cart.length===0){
      console.log("无数据")
      return;
    }
    //获取购物车并请求修改
    const userInfo = wx.getStorageSync('userinfo')
    let param = {
      userId:userInfo.id,
      carts:JSON.stringify(cart)
    }
    const result = await request({ url: "shopCart/setCart", data: param, method: 'POST' });
  },
  handleItemTab(e){
    const {index,typeid} = e.currentTarget.dataset;
    let toView = '';
    if(typeid===0){
      toView = 'right_new'
    }else{
      toView = 'right_'+typeid
    }
    this.setData({
      currentIndex:index,
      toView:toView,
      cp_index: index,
    })
  },
  changeCart(cart){
    wx.setStorageSync('cart', cart)
    this.setData({
      cart
    })
  },
  handleAddEdit(e){
    let userinfo = wx.getStorageSync('userinfo');
    if(userinfo===null || userinfo===""){
      wx.navigateTo({
        url: '/pages/login/index'
      })
      return
    }
    const {id,operation} = e.currentTarget.dataset;
    let {cart,products,cartData} = this.data;
    const index = cart.findIndex(v=>v.goodsId===id)
    products = products.filter(v=>v.id===id)
    if(index>=0&&operation===1){//加购过且操作为加
      cart[index].amount++;
      var pruductCount = cartData[id] ? cartData[id] : 0;
      cartData[id] = pruductCount+operation;
    }else if(index>=0&&operation===-1){//加购过且操作为减
      if(cart[index].amount===1){
        delete cartData[id];
        cart.splice(index,1);
      }else{
        var pruductCount = cartData[id] ? cartData[id] : 0;
        cartData[id] = pruductCount+operation;
        cart[index].amount--;
      }
    }else{
      let cobj = {
        id:null,
        goodsId:id,
        amount:1,
        userId:userinfo.id,
        brandName:products[0].brandName,
        name:products[0].name,
        price:products[0].price,
        stock:products[0].stock,
        file:products[0].file,
        isCheck:true
      }
      cart.push(cobj);
      var pruductCount = cartData[id] ? cartData[id] : 0;
      cartData[id] = pruductCount+operation;
    }
    this.setData({
      cartData
    });
    this.changeCart(cart);
  },
  bindscroll: function (e) {
    var zindex = this.data.zindex;
    var oneShow = this.data.oneShow;
    let scrollTop = e.detail.scrollTop;
    let scrollArr = this.data.heightArr;
    for (let i = 0; i < scrollArr.length; i++) {
      if (scrollTop >= 0 && scrollTop < scrollArr[0]) {
        if (oneShow) {
          console.log('==============aaa' + scrollTop + "==" + scrollArr[0]);
          this.setData({
            cp_index: 0,
            leftTop: 0,
            zindex: 0,
            oneShow: false
          })
          return
        }
      } else if (scrollTop >= (scrollArr[i - 1]) && scrollTop < scrollArr[i]) {
        if (i != zindex) {
          console.log('==============bbb' + i + scrollTop + "==" + scrollArr[i]);
          this.setData({
            oneShow: true,
            zindex: i,
            cp_index: i,
            leftTop: i * this.data.left_item_height
          })
        }
      }
    }
  }

})